package com.dule.Medic.service_hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import com.dule.Medic.beans.MedEntryBean;
import com.dule.Medic.beans.PatientBean;
import com.dule.Medic.model.Doctor;
import com.dule.Medic.model.MedEntry;
import com.dule.Medic.model.Patient;
import com.dule.Medic.service.PatientService;

public class PatientHibernateService implements PatientService 
{

private final Session session;
	
	public PatientHibernateService(Session session) {
		
		this.session = session; 
	}
	public Long save(Patient patient) 
	{
		Long id = (Long) session.save(patient);
		return  id;
	}
	
	public boolean update(Patient patient)
	{
		session.merge(patient);
		return true;
	}
	
	@SuppressWarnings("unchecked")
	public List<Patient> retrieveAll() 
	{
		List<Patient> patients=session.createCriteria(PatientBean.class).list(); 
		return patients;
	}

	public Patient retrieveOne(Patient patient) {
		Criteria crit = session.createCriteria(PatientBean.class).add(Restrictions.eq("medInsNo", patient.getMedInsNo()));    
		return (Patient	) crit.uniqueResult();  
	}
	
	public Patient retrieveOne(Long Id) {
		Criteria crit = session.createCriteria(PatientBean.class).add(Restrictions.eq("id", Id));    
		return (Patient	) crit.uniqueResult();  
	}
	
	public boolean deletePatient(Patient patient)
	{
		patient.getMedEntries().size();	
		for (int i = 0 ;i<patient.getMedEntries().size();i++)
		{	
				MedEntry me=patient.getMedEntries().get(i);
				Doctor dr=me.getDoctor();
				patient.RemoveMedEntry(me);
				session.merge(patient);
				dr.RemoveMedEntry(dr.getMedEntryById(me.getId()));
				session.merge(dr);
				session.delete(session.load(MedEntryBean.class, me.getId()));
				i--;
		}
		
		session.delete(session.load(PatientBean.class, patient.getId()));
		return true;
		
		
	}
	
	

	



}
